<template>
  <div>
    <el-row>
      <el-col :span="22" :offset="1">
        <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
          <el-tab-pane label="实时行情" name="first">
              <el-button size="mini" @click="oneDayKLine">1日K线</el-button>
              <el-button size="mini" @click="twoDayKLine">2日K线</el-button>
              <el-button size="mini" @click="threeDayKLine">3日K线</el-button>
          </el-tab-pane>
          <el-tab-pane label="数据分析" name="second">
              <el-button size="mini">SMA</el-button>
              <el-button size="mini">EMA</el-button>
              <el-button size="mini">APO</el-button>
              <el-button size="mini">MACD</el-button>
              <el-button size="mini">BBANDS</el-button>
              <el-button size="mini">RSI</el-button>
          </el-tab-pane>
          <!--
          <el-tab-pane label="策略实盘模拟" name="third">
              策略实盘模拟
          </el-tab-pane>
          <el-tab-pane label="常见策略介绍" name="fourth">
              常见策略介绍
          </el-tab-pane>
          -->
        </el-tabs>
      </el-col>
    </el-row>
    <el-main>
      <el-row>
            <el-col v-loading="isLoading" :span="10" :offset="1">
              <div :id="id" :class="className" :style="{height:height,width:width}" />
            </el-col>
            <el-col :span="11" :offset="1">
              <h1> {{ state1 }} </h1>
              <el-autocomplete
                style="width: 100%"
                class="inline-input"
                v-model="state1"
                :fetch-suggestions="querySearch"
                placeholder="请输入内容"
                @select="handleSelect"
              >
              </el-autocomplete>
                <el-table
                  v-if="!isChatVisiable"
                  :data="stockList"
                  border
                  height="200"
                  style="width: 100%; margin-top:20px; margin-bottom:20px;"
                >
                <el-table-column
                  prop="day"
                  label="时间"
                  style="width: 100%"
                />
                <el-table-column
                  prop="close"
                  label="价格"
                  style="width: 100%"
                />
                <el-table-column
                  prop="positions"
                  label="投入"
                  style="width: 100%"
                />
                <el-table-column
                  prop="cash"
                  label="现金"
                  style="width: 100%"
                />
               <el-table-column
                  prop="total"
                  label="账户总额"
                  style="width: 100%"
                />
                <el-table-column
                  prop="buysellsig"
                  label="策略推荐"
                  :formatter="positionsFormat"
                  style="width: 100%"
                />
              </el-table>
              <el-card class="box-card">
                <div slot="header" class="clearfix">
                  <el-button style="padding: 8px 1" type="info" @click="StartSyncData">启动</el-button>
                  <el-button style="padding: 8px 1" type="info" @click="StopSyncData">暂停</el-button>
                </div>
                <div v-for="o in messages" class="text item">
                  {{ o }}
                </div>
              </el-card>
            </el-col>
      </el-row>
    </el-main>
  </div>
</template>

<style>

</style>

<script>

import echarts from 'echarts'
import resize from './mixins/resize'
import settings from '@/settings'
const axios = require('axios');

import Cookies from 'js-cookie'

export default {
  name: 'Stock',
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    id: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '600px'
    }
  },
  data() {
    return {
      restaurants: [],
      state1: '',
      state2: '',
      options: [],
      activeName: 'first',
      value: 'sz000001',
      chart: null,
      activeIndex: '2',
      currentDate: new Date(),
      isCollapse: false,
      dateList: [],
      messages: [],
      timer: '',
      stockList: [],
      averageNavList: [],
      openList: [],
      closeList: [],
      lowList: [],
      highList: [],
      fundTransactionList: [],
      rowData: [],
      isLoading: false,
      stock_id: '',
      isAdmin: false,
      screenWidth: document.body.clientWidth,
    }
  },
  watch: {
    screenWidth(val) {
      if (!this.timer) {
        this.screenWidth = val
        this.timer = true
        const that = this
        setTimeout(function() {
          if (that.screenWidth < 1000) {
            that.isCollapse = true
          } else {
            that.isCollapse = false
          }
          that.timer = false
        }, 400)
      }
    }
  },
  created() {
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
    window.clearInterval(this.timer);
  },
  mounted() {
    const that = this
    window.onresize = () => {
      return (() => {
        window.screenWidth = document.body.clientWidth
        that.screenWidth = window.screenWidth
      })()
    }
    this.stock_id = "sz000001"
    this.state1 = "平安银行"
    this.getStockTranList(this.stock_id, 48)
    this.getStockList()
  },
  methods: {
    handleClick(tab, event) {
      console.log(tab, event);
    },
    oneDayKLine() {
      this.getStockTranList(this.stock_id, 48)
    },
    twoDayKLine() {
      this.getStockTranList(this.stock_id, 96)
    },
    threeDayKLine() {
      this.getStockTranList(this.stock_id, 144)
    },
    querySearch(queryString, cb) {
      var restaurants = this.restaurants;
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    handleSelect(item) {
      this.stock_id = item.address
      this.SyncStockData()
    },
    SyncStockData(){ 
      let this_ = this
      axios.get(settings.baseURL + '/api/stocktransactionrecord-sync/' + this.stock_id + '/')
      .then(function (response) {
        var myDate = new Date();
        this_.messages.unshift(myDate.toLocaleString() + '-' + response.data)
        while(this_.messages.length > 5) {
          this_.messages.pop()
        }
        this_.getStockTranList(this_.stock_id, 48)
      })
      .catch(function (error) {
        this_.isLoading = false
      })
    },
    StartSyncData(){
      this.messages.unshift("开始执行"); 
      this.timer = setInterval(this.SyncStockData, 10000);
    },
    StopSyncData(){
      this.messages.unshift("暂停执行"); 
      window.clearInterval(this.timer);
    },
    positionsFormat(row, column) {
      switch(row.buysellsig) {
        case 0.0:
          return '无操作';
        case 1.0:
          return '买入';
        case -1.0:
          return '卖出';
        default:
          return '未知';
      }
    },
    initKLineData() {
      this.chart = echarts.init(document.getElementById(this.id))
      this.chart.setOption({
        dataZoom: [
          {
            type: "inside"
          }
        ],
        tooltip: {
        trigger: "item",
        axisPointer: {
            animation: false,
            type: "cross",
            crossStyle: {
                color: "#376DF4"
            }
          }
        },
        xAxis: {
          type: "category",
          data: this.dateList
        },
        yAxis: {
          scale: true
        },
        series: [
          {
            type: "candlestick",
            itemStyle: {
              normal: {
                color: "#ED1C24",
                borderColor: "#ED1C24",
                color0: "#008000",
                borderColor0: "#008000"
              }
            },
            data: this.rowData
          }
        ]
      })
      this.rowData = []
      this.dateList = []
    },
    initChart() {
      this.chart = echarts.init(document.getElementById(this.id))
      const colors = ['#5470C6', '#EE6666']
      this.chart.setOption({
        color: colors,
        tooltip: {
          trigger: 'none',
          axisPointer: {
            type: 'cross'
          }
        },
        legend: {
          data: ['实时价格(¥)', '实时价格(¥)']
        },
        grid: {
          top: 70,
          bottom: 50
        },
        xAxis: [
          {
            type: 'category',
            axisTick: {
              alignWithLabel: true
            },
            axisLine: {
              onZero: false,
              lineStyle: {
                color: colors[1]
              }
            },
            axisPointer: {
              label: {
                // formatter: function (params) {
                //   return '降水量  ' + params.value + (params.seriesData.length ? '：' + params.seriesData[0].data : '');
                // }
              }
            },
            data: this.dateList
          },
          {
            type: 'category',
            axisTick: {
              alignWithLabel: true
            },
            axisLine: {
              onZero: false,
              lineStyle: {
                color: colors[0]
              }
            },
            axisPointer: {
              label: {
                // formatter: function (params) {
                //     return '降水量  ' + params.value
                //         + (params.seriesData.length ? '：' + params.seriesData[0].data : '');
                // }
              }
            },
            data: this.dateList
          }
        ],
        yAxis: [
          {
            type: 'value'
          }
        ],
        series: [
          {
            name: '实时价格(¥)',
            type: 'line',
            xAxisIndex: 1,
            smooth: true,
            emphasis: {
              focus: 'series'
            },
            data: this.averageNavList
          },
          {
            name: '实时价格(¥)',
            type: 'line',
            smooth: true,
            emphasis: {
              focus: 'series'
            },
            data: this.averageNavList
          }
        ]
      })
    },
    getStockList() {
      let this_ = this
      axios.get(settings.baseURL + '/api/get-sh-company/')
      .then(function (response) {
        for(var i = 0; i < response.data.COMPANY_ABBR.length; i++) {
          // this_.options.push( {'value': 'sh' + response.data.COMPANY_CODE[i], 'label': '深沪' + response.data.COMPANY_ABBR[i]} )
          this_.restaurants.push( {'value': response.data.COMPANY_ABBR[i] , 'address':  'sh' + response.data.COMPANY_CODE[i]} )
        }
        axios.get(settings.baseURL + '/api/get-sz-company/')
        .then(function (response) {
          for(var i = 0; i < response.data.COMPANY_ABBR.length; i++) {
            // this_.options.push( {'value': 'sz' + response.data.COMPANY_CODE[i], 'label': '深圳' + response.data.COMPANY_ABBR[i]} )
            this_.restaurants.push( {'value': response.data.COMPANY_ABBR[i], 'address':  'sz' +  response.data.COMPANY_CODE[i]} )
          }
        }).catch(function (error) {
          console.log('error', error)
        })
      })
      .catch(function (error) {
        console.log('error', error)
      })
    },
    getStockTranList(id, items) {
      this.isLoading = true
      let this_ = this
      axios.get(settings.baseURL + '/api/stocktransactionrecord-list/' + id + '/' + items +'/')
      .then(function (response) {
        var obj = JSON.parse(response.data)
        this_.fundTransactionList = obj.data
        this_.stockList = obj.data
        this_.stockList = this_.stockList.reverse()
        this_.dateList = []
        this_.averageNavList = []
        var raw = []
        for(var i = 0; i < this_.fundTransactionList.length; i++) {
          this_.dateList.unshift(this_.fundTransactionList[i].day)
          this_.averageNavList.unshift(this_.fundTransactionList[i].close)
          raw.push(parseFloat(this_.fundTransactionList[i].open_price))
          raw.push(parseFloat(this_.fundTransactionList[i].close))
          raw.push(parseFloat(this_.fundTransactionList[i].low))
          raw.push(parseFloat(this_.fundTransactionList[i].high))
          this_.rowData.unshift(raw)
          raw = []
        }
        this_.isLoading = false
        // this_.initChart()
        this_.initKLineData()
      })
      .catch(function (error) {
        console.log(error)
        this_.isLoading = false
      })
    },
    toCopyright() {
      this.$router.push({
        path: `/copyright`
      })
    },
    onOptionsChange() {
      this.stock_id = this.value
      this.SyncStockData()
    }
  }
}
</script>
